import { getToken, isAuth } from '@/utils/auth';
import { menuStore } from '@/store/modules';
import { IMenu } from '@/models/menu.interface';

import { Router } from 'vue-router';

export const routerGuard = (router: Router) => {
  router.beforeEach((to, from, next) => {
    const routes = menuStore.interceptRoutes;

    const meta = to.meta as IMenu;
    if (isAuth(meta.id, routes)) {
      const token = getToken();
      if (token) {
        next();
      } else {
        next('/');
      }
    } else {
      next();
    }
  });
};

export const statusGuard = (router: Router) => {
  const setTitle = (title: string) => {
    const defaultTitle = '默认标题';
    title = title ? `${title} - ${defaultTitle}` : defaultTitle;
    document.title = title;
  };

  router.afterEach(to => {
    window.scrollTo(0, 0);

    const { allMenu, setActiveIndex } = menuStore;
    let activeIndex = '';
    const meta = to.meta as IMenu;
    if (meta.menuType === 'router') {
      const parent = allMenu.find(menu => menu.id === meta.pid);
      activeIndex = parent?.id?.toString() ?? '';
    } else {
      activeIndex = meta.id?.toString();
    }
    setActiveIndex(activeIndex);
    setTitle(meta.menuName);

    // const color = to.path === '/' ? '#fff' : '#f8f8f8';
    // store.commit('global/setBackgroundColor', color);
  });
};
